<!-- 代码已包含 CSS：使用 TailwindCSS , 安装 TailwindCSS 后方可看到布局样式效果 -->
<template>
  <div class="app-container">
    <!-- 顶部信息栏 -->

    <div class="search-bar p-4 flex justify-between">
      <div class="flex items-center space-x-6">
        <div class="flex items-center space-x-2">
          <el-text class="!rounded-button">当前日期:</el-text>

          <el-date-picker
            v-model="selectDate"
            type="date"
            class="!w-[192px]"
            clearable
            placeholder="选择日期"
            @change="handleSearch"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          ></el-date-picker>
        </div>
        <!-- <div class="flex items-center space-x-2">
            <el-text class="text-gray-600 w-24">备注：</el-text>
            <el-input v-noSpace v-model="remark" placeholder="请输入备注信息"></el-input>
            <el-button type="primary" class="text-gray-600">提交备注</el-button>
          </div> -->
      </div>
      <div class="flex items-center space-x-4">
        <el-button
          type="primary"
          class="!rounded-button"
          v-hasPerm="'sys:scheduling:async'"
          @click="handleSync"
        >
          <el-icon class="mr-1">
            <Position />
          </el-icon>
          同步员工信息
        </el-button>
        <div class="flex items-center space-x-2">
          <el-button
            @click="
              () => {
                calendarDialogVisible = true;
                getMonthlyTableData(selectedMonthDate);
              }
            "
          >
            <el-icon class="mr-1">
              <Search />
            </el-icon>
            排班查询
          </el-button>
        </div>
      </div>
    </div>
    <el-dialog v-model="calendarDialogVisible" width="95%">
      <div class="flex items-center space-x-2 p-4 mb-4 mt-4 justify-between">
        <div class="flex items-center">
          <el-text class="text-gray-600 w-24">选择月份：</el-text>
          <el-date-picker
            v-model="selectedMonthDate"
            type="month"
            format="YYYY-MM"
            value-format="YYYY-MM"
            placeholder="选择月"
            @change="getMonthlyTableData(selectedMonthDate)"
          ></el-date-picker>
        </div>
        <div>
          <el-button type="primary" @click="downloadTable">下载</el-button>
        </div>
      </div>

      <div class="flex-1" title="月度排班表">
        <el-table
          :data="monthlyTableData"
          width="100%"
          height="500px"
          :border="true"
          size="small"
          id="educe-table"
        >
          <el-table-column label="员工数据" fixed="left" align="center">
            <el-table-column
              prop="employeeId"
              label="员工id"
              align="center"
              width="70px"
            ></el-table-column>
            <el-table-column
              prop="employeeName"
              label="姓名"
              align="center"
              width="70px"
            ></el-table-column>
          </el-table-column>
          <el-table-column :label="selectedMonthDate" align="center">
            <el-table-column
              v-for="day in monthDays"
              :key="day"
              :label="day.toString()"
              align="center"
              min-width="40px"
            >
              <template #default="scope">
                <el-text
                  type="primary"
                  size="small"
                  v-if="
                    scope.row.scheduleDates.some((e: any) => e.scheduleDate.slice(8, 10) == day)
                  "
                >
                  {{
                    scope.row.scheduleDates.filter(
                      (e: any) => e.scheduleDate.slice(8, 10) == day
                    )[0].processName
                  }}
                </el-text>
                <el-text v-else type="info" size="small">未排班</el-text>
              </template>
            </el-table-column>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>

    <el-card shadow="never">
      <!-- 主要内容区域 -->
      <div class="flex space-x-8">
        <!-- 左侧工序需求 -->
        <div class="w-1/4">
          <h2 class="text-lg font-medium mb-4">工序需求</h2>
          <div class="space-y-4" v-if="processList && processList.length">
            <div class="bg-white rounded-lg p-4 shadow-sm" v-for="(item, index) in processList">
              <div class="flex justify-between items-center">
                <el-text class="text-gray-900">{{ item.processName }}</el-text>
                <el-text class="text-blue-600">
                  {{ item.workerCount }}/{{ item.personPlan }}
                </el-text>
              </div>
            </div>
          </div>

          <div class="space-y-4 text-center" v-else>
            <div class="flex items-center space-x-2 w-full">
              <el-text class="text-gray-600">暂无单日排班工序</el-text>
            </div>
          </div>
        </div>
        <!-- 右侧排班表 -->
        <div class="flex-1">
          <div class="flex justify-between items-center mb-4">
            <h2 class="text-lg font-medium">排班表</h2>
            <!-- <div class="text-gray-600">
                总需求:
                <el-text class="text-blue-600">15人</el-text>
                | 已分配:
                <el-text class="text-blue-600">10人</el-text>
              </div> -->
          </div>
          <el-table :data="tableData" class="w-full">
            <el-table-column prop="employeeId" label="员工ID" align="center" />
            <el-table-column prop="employeeName" label="员工姓名" align="center" />
            <el-table-column prop="status" label="状态" align="center">
              <template #default="scope">
                <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
                  {{ scope.row.status ? "正常" : "请假" }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="processName" label="分配岗位" align="center">
              <template #default="scope">
                <el-button
                  v-if="
                    scope.row.status === 1 &&
                    processList.length &&
                    selectDate >= new Date().toISOString().slice(0, 10)
                  "
                  type="primary"
                  class="!rounded-button"
                  plain
                  v-hasPerm="'sys:scheduling:edit'"
                  @click="showAssignmentDialog(scope.row)"
                >
                  {{ scope.row.processName || "请选择工序" }}
                </el-button>
                <el-tag type="info" v-else-if="scope.row.processName" class="text-gray-400">
                  {{ scope.row.processName }}
                </el-tag>
                <el-tag type="info" v-else="scope.row.processName" class="text-gray-400">
                  不可排班
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分配岗位对话框 -->
          <el-dialog
            v-model="dialogVisible"
            title="分配岗位"
            width="30%"
            :show-close="true"
            class="!rounded-lg"
          >
            <div class="space-y-4">
              <div
                v-for="position in processList"
                :key="position.id"
                class="transition duration-300 hover:shadow-md"
              >
                <el-button
                  type="primary"
                  class="w-full !rounded-button flex items-center justify-between px-6 py-4 text-lg"
                  plain
                  @click="handleAssign(position)"
                >
                  <div class="flex items-center">
                    <el-icon class="text-xl mr-3">
                      <component
                        :is="
                          position.processName === 'cleaning'
                            ? 'Delete'
                            : position.processName === 'packing'
                              ? 'Box'
                              : 'Tools'
                        "
                      />
                    </el-icon>
                    <span>{{ position.processName }}</span>
                  </div>
                  <el-icon>
                    <ArrowRight />
                  </el-icon>
                </el-button>
              </div>
            </div>
          </el-dialog>
        </div>
      </div>
    </el-card>
  </div>
</template>
<script lang="ts" setup>
import { ref } from "vue";
import * as XLSX from "xlsx-js-style";
// import XLSX from "xlsx-js-style";
import { ElMessage } from "element-plus";
import { Position, Search } from "@element-plus/icons-vue";
import schedulingApi, { ProductionOrder, schedulingPageVO } from "@/api/prodManage/scheduling";

const dialogVisible = ref(false);
const currentWorker = ref<schedulingPageVO>();
const selectedMonthDate = ref(new Date().toISOString().slice(0, 7));

const positions = ref<ProductionOrder[]>();

const calendarDialogVisible = ref(false);

const tableData = ref<schedulingPageVO[]>();
const showAssignmentDialog = (row: any) => {
  if (selectDate.value < new Date().toISOString().slice(0, 10)) return;
  currentWorker.value = row;
  console.log(currentWorker.value);

  dialogVisible.value = true;
};
const handleAssign = (position: { processCode: string; processName: string; id: number }) => {
  if (currentWorker.value) {
    currentWorker.value.processCode = position.processCode;
    currentWorker.value.processName = position.processName;
    currentWorker.value.id = currentWorker.value.scheduleId;
    console.log(currentWorker.value);

    schedulingApi
      .saveSchedule({ ...currentWorker.value, scheduleDate: selectDate.value })
      .then((res: any) => {
        ElMessage.success("分配成功");
        handleSearch();
      })
      .catch((err) => {
        // ElMessage.error(`${err}`);
        handleSearch();
      });
  }
  dialogVisible.value = false;
};
const handleSync = () => {
  ElMessage.success("员工信息同步成功");
  handleSearch();
};
//获取当月的天数
const getDaysInMonth = (year: number, month: number) => {
  return new Date(year, month, 0).getDate();
};
//修改日期
const selectDate = ref(new Date().toISOString().slice(0, 10));
const monthDays = ref(
  getDaysInMonth(
    new Date(selectedMonthDate.value).getFullYear(),
    new Date(selectedMonthDate.value).getMonth() + 1
  )
);
// 生成月度排班数据
const monthlyTableData = ref();

//获取月度排版数据
const getMonthlyTableData = (date: string) => {
  monthDays.value = getDaysInMonth(new Date(date).getFullYear(), new Date(date).getMonth() + 1);
  schedulingApi
    .getMonthlyEmployeeSchedule(date)
    .then((res: any) => {
      console.log(res, "月度排版数据");

      monthlyTableData.value = res;
    })
    .catch((err) => {
      // ElMessage.error(`${err}`);
    });
};

//获取所有工序
const processList = ref<ProductionOrder[]>([]);
const getProcessList = (date: string) => {
  schedulingApi.getProcessList(date).then((res: any) => {
    processList.value = res;
    positions.value = res;
  });
};

const handleSearch = (date?: string) => {
  if (date) date = date;
  else date = selectDate.value;
  selectedMonthDate.value = date.slice(0, 7);
  schedulingApi.getPage(date).then((res: any) => {
    tableData.value = res;
  });
  getProcessList(date);
};

//下载表格
const downloadTable = () => {
  const table = document.getElementById("educe-table") as HTMLTableElement;
  if (table) {
    const ws = XLSX.utils.table_to_sheet(table, { raw: true });
    const wb = XLSX.utils.book_new();

    XLSX.utils.book_append_sheet(wb, ws, "月度排班表");
    console.log(wb, "wb");

    XLSX.writeFile(wb, `月度排班表_${selectedMonthDate.value}.xlsx`);
  } else {
    ElMessage.error("表格未找到");
  }
};
onMounted(() => {
  handleSearch(selectDate.value);
});
</script>
<style scoped></style>
